import axios from 'axios'
import Store from '@/store'
import router from '../router'

const request = axios.create({
  baseURL: 'http://toutiao.itheima.net'
})

request.interceptors.response.use(res => {
  return res
}, error => {
  console.dir(error)
  if (error.response.status === 401) {
    Store.commit('setToken', '')
    router.replace({ path: '/login?from=' + router.currentRoute.path })
  }
  return Promise.reject(error)
})

request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么, 如果vuex里有token携带在请求头中
  if (Store.state.token.length > 0 && config.headers.Authorization === undefined) {
    // 发起请求之前, 把token携带在请求头上(表明自己身份)
    config.headers.Authorization = 'Bearer ' + Store.state.token
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})
export default request
